package parknfly

import (
	"encoding/json"
	"fmt"
	"parking-lot-go-push/model"
	"parking-lot-go-push/model/cars"
	"parking-lot-go-push/model/order"
	"parking-lot-go-push/model/park"
	"parking-lot-go-push/mongodb"
)

type EntryStruct struct {
	mongodb.CarsEntryMongoDbStruct
}

// 入场通知
func (entryData EntryStruct) Entry() {
	parknflyPushLogger.Info(" ")
	parknflyPushLogger.Info("---入场推送---")
	jsonData, _ := json.Marshal(entryData)
	parknflyPushLogger.Info(fmt.Sprintf("参数:%s", string(jsonData)))

	//错误信息
	var err error

	//查询订单
	var orderData order.OrderStruct
	if _, err = orderData.FetchOrder(entryData.OrderNo, 0, 2); err != nil {
		parknflyPushLogger.Error(fmt.Sprintf("订单查询失败:%s", err.Error()))
		return
	}

	//查询泊安飞订单
	var orderParknflyStruct order.OrderParknflyStruct
	if _, err := orderParknflyStruct.FetchOrder(entryData.OrderNo, 0); err != nil {
		parknflyPushLogger.Error(fmt.Sprintf("泊安飞订单查询失败:%s", err.Error()))
		return
	}

	//超停状态
	abnormal, err := orderData.OverStop(entryData.ParkCode, 2, entryData.OrderNo)
	if err != nil {
		parknflyPushLogger.Error(err.Error())
		return
	}

	//查询泊安飞停车场信息
	var parkingLotParknflyData park.ParkingLotParknflyStruct
	model.GetModelDataFirst(
		model.Db,
		parkingLotParknflyData.TableName(),
		&parkingLotParknflyData,
		model.QueryOptions{
			Conditions: map[string]interface{}{
				"park_code": entryData.ParkCode,
			},
		})

	//推送泊安飞进场信息
	parknflyEntryPushData := map[string]interface{}{
		"parkKey":    parkingLotParknflyData.ParkKey,
		"parkCode":   entryData.ParkCode,
		"parkName":   entryData.ParkName,
		"carId":      entryData.CarNumber,
		"inTime":     entryData.InTime,
		"serialno":   entryData.SerialNo,
		"regionCode": entryData.RegionCode,
		"regionName": entryData.RegionName,
		"carnoColor": entryData.CarNoColor,
		"inPhoto":    entryData.InPhoto,
		"orderNo":    entryData.OrderNo,
	}

	var carsEntryStruct cars.CarsEntryStruct

	//加密信息计算
	parknflySigner := NewSigner()
	if err, _ := parknflySigner.CurlPostJson("carIn", parknflyEntryPushData); err != nil {
		parknflyPushLogger.Error("错误:推送失败", err.Error())

		//失败状态更新
		if err := carsEntryStruct.PushError(entryData.OrderNo, entryData.PushErrNum); err != nil {
			parknflyPushLogger.Error(err.Error())
		}

	} else {
		//成功状态更新
		if err := carsEntryStruct.PushSuccess(entryData.OrderNo, entryData.InTime, entryData.ParkCode, entryData.OrderType, abnormal); err != nil {
			parknflyPushLogger.Error(err.Error())
		}
	}
}
